package logic

import (
	"context"
	"errors"

	"go-zero-mall/app/admin/cmd/rpc/internal/svc"
	"go-zero-mall/app/admin/cmd/rpc/pd"
	"go-zero-mall/app/admin/model"
	"go-zero-mall/common/xerr"

	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

type AdminRegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAdminRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminRegisterLogic {
	return &AdminRegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 管理员-用户注册
func (l *AdminRegisterLogic) AdminRegister(in *pd.AdminParamReq) (*pd.CommonResp, error) {
	user, err := l.svcCtx.UmsAdminModel.FindOneByName(l.ctx, in.Username)
	if err != nil && err != model.ErrNotFound {
		return nil, errors.New(xerr.MapErrMsg(xerr.DB_ERROR))
	}
	if user != nil {
		return nil, errors.New("用户已经存在")
	}
	var userId int64
	if err := l.svcCtx.UmsAdminModel.Trans(l.ctx, func(ctx context.Context, session sqlx.Session) error {
		user := new(model.UmsAdmin)
		copier.Copy(&user, in)
		lastId, err := l.svcCtx.UmsAdminModel.InsertSession(ctx, session, user)
		if err != nil {
			return errors.New("数据插入错误")
		}
		userId, _ = lastId.LastInsertId()
		return nil
	}); err != nil {
		return nil, err
	}
	return &pd.CommonResp{Result: userId}, nil
}
